package com.example.exampleproject.base;

import android.annotation.SuppressLint;

import com.example.exampleproject.cache.NetCacheManager;
import com.example.exampleproject.entity.BaseResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public class BaseDataManager {

    @Inject
    Gson gson;

    protected <T, O extends BaseObserver<T>> Disposable subscribe(PublishSubject<T> publishSubject, O consumer) {
            publishSubject.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);
            return consumer.attachDisposable();
    }

    @SuppressLint("CheckResult")
    protected <T> void publish(Observable<T> observable, PublishSubject<T> publishSubject) {
        observable.compose(new HandleErrTransformer<>())
                .compose(new HandleBizErrTransformer<>())
                .compose(applyTransformer())
        .subscribe(publishSubject::onNext,
                publishSubject::onError);
    }

    protected <T> Observable<BaseResponse<T>> getNetCacheObservable(String url) {
        String cacheContent = NetCacheManager.redNetCache(url);
        Type type = new TypeToken<BaseResponse<T>>(){}.getType();
        BaseResponse<T> entity = gson.fromJson(cacheContent, type);
        return entity == null ? Observable.empty() : Observable.just(entity);
    }

    private <T> ObservableTransformer<T, T> applyTransformer() {
        return upstream -> upstream.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }
}
